/*
 * File     : X86_64ThunkManagerDelegate.java
 * Created  : 7 Jan 2012
 *
 * Copyright © 2011 Matthew Wilson (mj. {my-surname} .uk {at} gmail.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.dni.internal.callback;

import java.nio.ByteBuffer;

import com.googlecode.dni.internal.callback.ThunkManager.ThunkManagerDelegate;
import com.googlecode.dni.type.Pointer;

/**
 * Implementation of {@link ThunkManagerDelegate} for X86.
 *
 * @author Matthew Wilson
 */
public final class X86ThunkManagerDelegate extends AbstractThunkManagerDelegate
{

    /** Conveniently, both the jump and entry table entries are 16 bytes long. */
    private static final int ENTRY_SIZE = 16;

    private final int thunkAddress;


    /**
     * @param thunkAddress
     *            the generic thunk address
     */
    public X86ThunkManagerDelegate( final Pointer thunkAddress )
    {
        if ( Pointer.isNull( thunkAddress ) )
        {
            throw new IllegalArgumentException();
        }

        this.thunkAddress = (int) thunkAddress.address();

        assert NATIVE_ENTRY_SIZE == ENTRY_SIZE;
    }

    /** {@inheritDoc} */
    @Override
    public int getJumpEntrySize()
    {
        return ENTRY_SIZE;
    }

    /** {@inheritDoc} */
    @Override
    public int getInfoEntrySize()
    {
        return ENTRY_SIZE;
    }

    /** {@inheritDoc} */
    @Override
    public void writeJumpEntry( final ByteBuffer jumpBuffer, final long infoAddress )
    {
        // Then 0xc - 0xf inclusive are 0xCC (INT 3)

        //  0:   bb ?? ?? ?? ??    mov %ebx, <address of info>
        jumpBuffer.put( (byte) 0xbb );
        jumpBuffer.putInt( (int) infoAddress );

        //  5:   b8 ?? ?? ?? ??    mov %eax, <address of function>
        jumpBuffer.put( (byte) 0xb8 );
        jumpBuffer.putInt( this.thunkAddress );

        //  a:   ff e0             jmp [ %eax ]
        jumpBuffer.put( (byte) 0xff );
        jumpBuffer.put( (byte) 0xe0 );

        // fill with: int 3
        while ( jumpBuffer.hasRemaining() )
        {
            jumpBuffer.put( (byte) 0xcc );
        }
    }

}
